package cn.anquing.demo.mybatisplus.component.CodeGennerator;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @author wangquanqing
 * @date 2021/4/18 0:01
 */
public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (null != ipt && !"".equals(ipt) ) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // #1 自定义工程的根目录（pom.xml所在目录）
        final String  projectPath = "D:\\project\\mybatis-plus-demo";
//        final String  projectPath = "D:\\project\\yueyun-fastdp-finance\\fastdp-finance-system";
        System.out.println(projectPath);

        //全局配置
        GlobalConfig globalConfig = buildGC(projectPath,"");
        mpg.setGlobalConfig(globalConfig);

        // #2 自定义数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://127.0.0.1:3306/mybatis_plus_demo?characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false");
        dsc.setUsername("root");
        dsc.setPassword("root");
        //  5.8以下版本驱动需要更改为com.mysql.jdbc.Driver
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
//        dsc.setDriverName("com.mysql.jdbc.Driver");
        mpg.setDataSource(dsc);

        // #3 自定义包配置
        PackageConfig pc = new PackageConfig()
                .setParent("cn.anquing.demo.mybatisplus.code")
                .setController("controller")
                .setEntity("pojo.entity")
                .setMapper("dao")
                .setService("service")
                .setServiceImpl("service.impl")
                .setXml("mapper.xml");
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
//        String templatePath = "/templates/dao.xml.ftl";
        // 如果模板引擎是 velocity
         String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return projectPath + "/src/main/resources/dao-xml"
                        + "/" + tableInfo.getEntityName() + "Dao" + StringPool.DOT_XML;
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        // 指定自定义模板路径，注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
         templateConfig.setEntity("/templates/entity.java");

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = buildStrategy();
        mpg.setStrategy(strategy);
        mpg.execute();
    }


    private static StrategyConfig buildStrategy() {

        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        List<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime);
        tableFills.add(updateTime);

        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.baomidou.mybatisplus.extension.activerecord.Model");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setSuperControllerClass("");
        strategy.setInclude(scanner("表名，多个英文逗号分割").split(","));
        strategy.setControllerMappingHyphenStyle(false);
        strategy.setEntityTableFieldAnnotationEnable(true);
        strategy.setVersionFieldName("version");
        strategy.setLogicDeleteFieldName("del_flag");
        strategy.setTableFillList(tableFills);
        return strategy;
    }

    private static GlobalConfig buildGC(String projectPath,String entityName) {
        // #4 自定义全局配置（主要是Author）、是否指定实体类名，如果要指定，每次只能生成一个表
        if (StringUtils.isEmpty(entityName)) {
            entityName = "%s";
        }
        GlobalConfig gc = new GlobalConfig();
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("wqq");
        gc.setOpen(false);
        gc.setBaseResultMap(true);
        gc.setBaseColumnList(true);
        gc.setEnableCache(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(true);
        gc.setMapperName(entityName + "Dao");
        gc.setServiceName("I"+entityName + "Service");
        gc.setServiceImplName(entityName + "ServiceImpl");
        gc.setControllerName(entityName + "Controller");
        gc.setSwagger2(true);
        gc.setEntityName(entityName);
        return gc;
    }
}
